package top.zywork.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.zywork.annotation.SysLog;
import top.zywork.common.BeanUtils;
import top.zywork.common.BindingResultUtils;
import top.zywork.common.StringUtils;
import top.zywork.dos.MallCommissionGrantConfig;
import top.zywork.dto.PagerDTO;
import top.zywork.dto.RoleDTO;
import top.zywork.enums.ActiveStatusEnum;
import top.zywork.enums.SysConfigEnum;
import top.zywork.query.RoleQuery;
import top.zywork.service.RoleService;
import top.zywork.service.SysConfigService;
import top.zywork.vo.PagerVO;
import top.zywork.vo.ResponseStatusVO;
import top.zywork.vo.RoleVO;

import java.util.ArrayList;
import java.util.List;

/**
 * RoleController控制器类<br/>
 *
 * 创建于2019-06-26<br/>
 *
 * @author http://zywork.top 王振宇
 * @version 1.0
 */
@RestController
@RequestMapping("/role")
@Slf4j
public class RoleController extends BaseController {

    private RoleService roleService;

    private SysConfigService sysConfigService;

    @PostMapping("admin/save")
    @SysLog(description = "后台保存RoleVO")
    public ResponseStatusVO save(@RequestBody @Validated RoleVO roleVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        roleService.save(BeanUtils.copy(roleVO, RoleDTO.class));
        return ResponseStatusVO.ok("添加成功", null);
    }

    @PostMapping("admin/batch-save")
    @SysLog(description = "后台批量保存RoleVO")
    public ResponseStatusVO saveBatch(@RequestBody @Validated List<RoleVO> roleVOList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        roleService.saveBatch(BeanUtils.copyListObj(roleVOList, RoleDTO.class));
        return ResponseStatusVO.ok("批量添加成功", null);
    }

    @GetMapping("admin/remove/{id}")
    @SysLog(description = "后台删除RoleVO")
    public ResponseStatusVO removeById(@PathVariable("id") Long id) {
        roleService.removeById(id);
        return ResponseStatusVO.ok("删除成功", null);
    }

    @PostMapping("admin/batch-remove")
    @SysLog(description = "后台批量删除RoleVO")
    public ResponseStatusVO removeByIds(@RequestBody String[] ids) {
        roleService.removeByIds(StringUtils.strArrayToLongArray(ids));
        return ResponseStatusVO.ok("批量删除成功", null);
    }

    @PostMapping("admin/update")
    @SysLog(description = "后台更新RoleVO")
    public ResponseStatusVO update(@RequestBody @Validated RoleVO roleVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        int updateRows = roleService.update(BeanUtils.copy(roleVO, RoleDTO.class));
        if (updateRows == 1) {
            return ResponseStatusVO.ok("更新成功", null);
        } else {
            return ResponseStatusVO.dataError("数据版本号有问题，在此更新前数据已被更新", null);
        }
    }

    @PostMapping("admin/batch-update")
    @SysLog(description = "后台批量更新RoleVO")
    public ResponseStatusVO updateBatch(@RequestBody @Validated List<RoleVO> roleVOList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        roleService.updateBatch(BeanUtils.copyListObj(roleVOList, RoleDTO.class));
        return ResponseStatusVO.ok("批量更新成功", null);
    }

    @PostMapping("admin/active")
    @SysLog(description = "后台激活或冻结RoleVO")
    public ResponseStatusVO active(@RequestBody RoleVO roleVO) {
        roleService.update(BeanUtils.copy(roleVO, RoleDTO.class));
        return ResponseStatusVO.ok("激活或冻结成功", null);
    }

    @PostMapping("admin/batch-active")
    @SysLog(description = "后台批量激活或冻结RoleVO")
    public ResponseStatusVO activeBatch(@RequestBody @Validated List<RoleVO> roleVOList) {
        roleService.updateBatch(BeanUtils.copyListObj(roleVOList, RoleDTO.class));
        return ResponseStatusVO.ok("批量激活或冻结成功", null);
    }

    @GetMapping("admin/one/{id}")
    public ResponseStatusVO getById(@PathVariable("id") Long id) {
        RoleVO roleVO = new RoleVO();
        Object obj = roleService.getById(id);
        if (obj != null) {
            roleVO = BeanUtils.copy(obj, RoleVO.class);
        }
        return ResponseStatusVO.ok("查询成功", roleVO);
    }

    @GetMapping("admin/all")
    public ResponseStatusVO listAll() {
        PagerDTO pagerDTO = roleService.listAll();
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), RoleVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @PostMapping("admin/all-cond")
    public ResponseStatusVO listAllByCondition(@RequestBody RoleQuery roleQuery) {
        PagerDTO pagerDTO = roleService.listAllByCondition(roleQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), RoleVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    /**
     * 获取可访问后台的角色
     * @return
     */
    @GetMapping("any/backend-roles")
    public ResponseStatusVO listAllBackendRoles() {
        RoleQuery roleQuery = RoleQuery.builder().visitBackend((byte) 1).isActive(ActiveStatusEnum.ACTIVE.getValue().byteValue()).build();
        PagerDTO pagerDTO = roleService.listAllByCondition(roleQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), RoleVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @PostMapping("admin/pager-cond")
    public ResponseStatusVO listPageByCondition(@RequestBody RoleQuery roleQuery) {
        PagerDTO pagerDTO = roleService.listPageByCondition(roleQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), RoleVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    /**
     * 获取分销角色
     * @return
     */
    @GetMapping("admin/list-distribution-roles")
    public ResponseStatusVO listDistributionRoles() {
        MallCommissionGrantConfig mallCommissionGrantConfig = sysConfigService.getByName(SysConfigEnum.MALL_COMMISSION_GRANT_CONFIG.getValue(), MallCommissionGrantConfig.class);
        return listRoles(mallCommissionGrantConfig.getDistributionRoles());
    }

    /**
     * 获取顶级分销商角色
     * @return
     */
    @GetMapping("admin/list-top-distribution-roles")
    public ResponseStatusVO listTopDistributionRoles() {
        MallCommissionGrantConfig mallCommissionGrantConfig = sysConfigService.getByName(SysConfigEnum.MALL_COMMISSION_GRANT_CONFIG.getValue(), MallCommissionGrantConfig.class);
        return listRoles(mallCommissionGrantConfig.getTopDistributionRoles());
    }

    /**
     * 获取提货点角色
     * @return
     */
    @GetMapping("admin/list-pickup-distribution-roles")
    public ResponseStatusVO listPickupDistributionRoles() {
        MallCommissionGrantConfig mallCommissionGrantConfig = sysConfigService.getByName(SysConfigEnum.MALL_COMMISSION_GRANT_CONFIG.getValue(), MallCommissionGrantConfig.class);
        return listRoles(mallCommissionGrantConfig.getPickupDistributionRoles());
    }

    private ResponseStatusVO listRoles(String roles) {
        PagerVO pagerVO = new PagerVO();
        pagerVO.setRows(new ArrayList<>());
        pagerVO.setTotal(0L);
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(roles)) {
            PagerDTO pagerDTO = roleService.listRoles(roles.split(","));
            pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
            pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), RoleVO.class));
            return ResponseStatusVO.ok("查询成功", pagerVO);
        }
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @Autowired
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    @Autowired
    public void setSysConfigService(SysConfigService sysConfigService) {
        this.sysConfigService = sysConfigService;
    }
}
